//
//  AboutController.m
//  iCarStyle
//
//  Created by liu nian on 13-9-9.
//  Copyright (c) 2013年 liunian. All rights reserved.
//

#import "AboutController.h"
#import "UMFeedbackViewController.h"
#import "UMFeedback.h"
#import "RescueController.h"
#import <MessageUI/MessageUI.h>
#import "DataEnvironment.h"
#import "ALAlertBanner.h"
#import "AppDelegate.h"

@interface AboutController ()<UITableViewDataSource,UITableViewDelegate,UIAlertViewDelegate,MFMailComposeViewControllerDelegate>
@property (nonatomic, retain) UITableView   *tableView;
@end

@implementation AboutController

- (id)init
{
    self = [super init];
    if (self) {
        // Custom initialization
        self.title = @"关于";
    }
    return self;
}
- (NSString *)tabTitle
{
	return self.title;
}
- (NSString *)tabImageName
{
	return @"image-8";
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    [self.tableView reloadData];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated{
    [MobClick beginLogPageView:@"关于视图"];
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [MobClick endLogPageView:@"关于视图"];
}
- (void)back{
    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
}

-(long)fileSizeForDir:(NSString*)path//计算文件夹下文件的总大小
{
    long size = 0;
    NSFileManager *fileManager = [[NSFileManager alloc] init];
    NSArray* array = [fileManager contentsOfDirectoryAtPath:path error:nil];
    for(int i = 0; i<[array count]; i++)
    {
        NSString *fullPath = [path stringByAppendingPathComponent:[array objectAtIndex:i]];
        
        BOOL isDir;
        if ( !([fileManager fileExistsAtPath:fullPath isDirectory:&isDir] && isDir) )
        {
            NSDictionary *fileAttributeDic = [fileManager attributesOfItemAtPath:fullPath error:nil];
            size += fileAttributeDic.fileSize;
        }
        else
        {
            [self fileSizeForDir:fullPath];
        }
    }
    return size;
    
}
//单位:MB
- (NSString *)sizeCache{
    NSArray*paths=NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask,YES);
    NSString*cachesDir = [paths objectAtIndex:0];
    NSString *ImageCachePath = [cachesDir stringByAppendingPathComponent:@"ImageCache"];
    long ImageCacheSize = [self fileSizeForDir:ImageCachePath];
    
    NSString *urlCachePath = [cachesDir stringByAppendingPathComponent:@"URLCACHE"];
    long urlCacheSize = [self fileSizeForDir:urlCachePath];
    
    long totalSize = ImageCacheSize + urlCacheSize;
    const unsigned int bytes = 1024*1024 ;   //字节数，如果想获取KB就1024，MB就1024*1024
    NSString *string = [NSString stringWithFormat:@"%.2f",(1.0 *totalSize/bytes)];
    BMLog(@"ImageCacheSize:%ld,urlCacheSize:%ld",ImageCacheSize,urlCacheSize);
    return string;
}
- (BOOL)cleanAllCache{
    [[SDImageCache sharedImageCache] clearDisk];
    NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask,YES) objectAtIndex:0];
    NSString *urlCache_doc = [cachePath stringByAppendingPathComponent:@"URLCACHE"];
    
    if ([[NSFileManager defaultManager] fileExistsAtPath:urlCache_doc]) {
        [[NSFileManager defaultManager] removeItemAtPath:urlCache_doc error:nil];
    }
    return YES;
}

#pragma mark UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 0) {
        return;
    }
    switch (alertView.tag) {
        case 10011:
        {
        }
            break;
        case 10012:
        {
        }
            break;
        case 10013:
        {
            ALAlertBannerStyle randomStyle = ALAlertBannerStyleSuccess;
            NSString *aTitle = @"成功";
            NSString *aContent = @"缓存清理成功!";
            if (![self cleanAllCache]) {
                aTitle = @"失败";
                aContent = @"清理缓存失败,请重试!";
                randomStyle = ALAlertBannerStyleFailure;
            }
            
            AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
            ALAlertBannerPosition position = ALAlertBannerPositionUnderNavBar;
            ALAlertBanner *banner = [ALAlertBanner alertBannerForView:appDelegate.window style:randomStyle position:position title:aTitle subtitle:aContent tappedBlock:^(ALAlertBanner *alertBanner) {
                [alertBanner hide];
            }];
            banner.secondsToShow = 2;
            banner.showAnimationDuration = 0.25;
            banner.hideAnimationDuration = 0.20;
            [banner show];
            
            [self.tableView reloadData];
        }
            break;
            
        default:
            break;
    }
}

#pragma mark UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    switch (section) {
        case 0:
        {
            return 2;
        }
            break;
        case 1:
        {
            return 3;
        }
            break;
        default:
            break;
    }
    return 0;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    switch (section) {
        case 0:
        {
            return @"程序";
        }
            break;
        case 1:
        {
            return @"其他";
        }
            break;
        default:
            break;
    }
    return @"其他";
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
    }
    switch (indexPath.section) {
            
        case 0:
        {
            switch (indexPath.row) {
                case 0:
                {
                    cell.textLabel.text = @"救援电话";
                    [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
                }
                    break;
                case 1:
                {
                    cell.textLabel.text = @"清理缓存文件";
                    cell.detailTextLabel.text = [NSString stringWithFormat:@"%@MB",[self sizeCache]];
                }
                    break;
                default:
                    break;
            }
        }
            break;
        case 1:
        {
            switch (indexPath.row) {
                case 0:
                {
                    cell.textLabel.text = @"给我们打分";
                }
                    break;
                case 1:
                {
                    [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
                    cell.textLabel.text = @"版本更新";
                }
                    break;
                case 2:
                {
                    [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
                    cell.textLabel.text = @"反馈和建议";
                }
                    break;
                default:
                    break;
            }
        }
            break;
        default:
            break;
    }
    return cell;
}


#pragma mark UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    switch (indexPath.section) {
        case 0:
        {
            switch (indexPath.row) {
                case 0:
                {
                    RescueController *controller = [[RescueController alloc] init];
                    [self.navigationController pushViewController:controller animated:YES];
                    
                }
                    break;
                case 1:
                {
                    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"确定清理缓存文件么?" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
                    [alert setTag:10013];
                    [alert show];
                    
                }
                    break;
                default:
                    break;
            }
        }
            break;
        case 1:
        {
            switch (indexPath.row) {
                case 0:
                {
                    NSString *appUrlString = [NSString stringWithFormat:@"itms-apps://itunes.apple.com/app/id%u?mt=8",kAPPID];
                    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:appUrlString]];
                    
                }
                    break;
                case 1:
                {
                    [MobClick checkUpdateWithDelegate:self selector:@selector(callBackSelectorWithDictionary:)];
                    
                }
                    break;
                case 2:
                {
                    MFMailComposeViewController *mailViewController = [[MFMailComposeViewController alloc] init];
                    
                    mailViewController.mailComposeDelegate = self;
                    
                    NSString *subject = [NSString stringWithFormat:@"反馈及建议:[汽车助手] 版本:%@",APP_VERSION];
                    [mailViewController setSubject:subject];
                [mailViewController setToRecipients:[NSArray arrayWithObject:@"iliunian@me.com"]];
            
                    [mailViewController setMessageBody:@"反馈正文..." isHTML:NO];
                    mailViewController.modalPresentationStyle = UIModalPresentationFormSheet;
                    [self.navigationController presentViewController:mailViewController animated:YES completion:nil];
                    
                }
                    break;
                default:
                    break;
            }
        }
            break;
        default:
            break;
    }
    
}

- (void)callBackSelectorWithDictionary:(NSDictionary *)appUpdateInfo{
    BMLog(@"%@",appUpdateInfo);
    BOOL update = [[appUpdateInfo objectForKey:@"update"] boolValue];
    if (update) {
        [MobClick checkUpdate:@"有新版本更新啦！" cancelButtonTitle:@"我爱怀旧" otherButtonTitles:@"我爱潮流"];
        
        
    }else{
        dispatch_async(dispatch_get_main_queue(), ^{
            AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
            ALAlertBannerStyle randomStyle = ALAlertBannerStyleSuccess;
            ALAlertBannerPosition position = ALAlertBannerPositionUnderNavBar;
            ALAlertBanner *banner = [ALAlertBanner alertBannerForView:appDelegate.window style:randomStyle position:position title:@"提示" subtitle:@"您使用的已经是最新的版本!" tappedBlock:^(ALAlertBanner *alertBanner) {
                NSLog(@"tapped!");
                [alertBanner hide];
            }];
            banner.secondsToShow = 2;
            banner.showAnimationDuration = 0.25;
            banner.hideAnimationDuration = 0.20;
            [banner show];
            return;
            
        });
    }
    
}
#pragma mark MFMailComposeViewControllerDelegate
- (void)mailComposeController:(MFMailComposeViewController *)controller
          didFinishWithResult:(MFMailComposeResult)result
                        error:(NSError *)error
{
	[controller dismissViewControllerAnimated:YES completion:nil];
}
#pragma mark - getter

- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.bounds), CGRectGetHeight(self.view.bounds) - 0)
                                                  style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        [_tableView setBackgroundView:nil];
        [_tableView setBackgroundColor:[UIColor whiteColor]];
        [self.view addSubview:_tableView];
    }
    return _tableView;
}

@end
